package lovedna.service;
import haxe.io.Bytes;
import haxe.io.BytesInput;
import haxe.io.BytesOutput;
import lovedna.core.IHandler;
import lovedna.core.IMessage;
import lovedna.event.EventDispatcher;
import lovedna.event.OutputEvent;
import lovedna.message.Error;
import php.Lib;
import php.Web;

/**
 * ...
 * @author liwei
 */

class Process extends Actor
{
	private var _output:OutPool;
	public function new() 
	{
		super();
		_output = new OutPool();
	}
	public function run():Void {
		var action:String = Web.getParamsString();
		if (action == "") {
			dispatchEvent(new OutputEvent(new Error(0, "not give an action")));
			return;
		}
		var post:String = Web.getPostData();
		if (post == "") {
			dispatchEvent(new OutputEvent(new Error(0, "not give data")));
			return;
		}
		action = action.toLowerCase();
		action = action.toUpperCase().substr(0, 1) + action.substr(1);
		var cls:Class<Dynamic> = Type.resolveClass("lovedna.handler."+action);
		if (cls == null) {
			dispatchEvent(new OutputEvent(new Error(0, "not found handler "+action)));
			return;
		}
		var obj:Dynamic = Type.createInstance(cls, []);
		if (Std.is(obj, IHandler)) {
			var handler:IHandler = cast(obj, IHandler);
			var out:BytesOutput = new BytesOutput();
			out.writeString(post);
			var input:BytesInput = new BytesInput(out.getBytes());
			input.readInt32();
			input.readString(input.readInt16());
			
			var output:BytesOutput = new BytesOutput();
			output.writeByte(19);
			output.writeString("a");
			Lib.print(output.getBytes());
			handler.run();
		}
	}
	public function getOut():Bytes {
		var b:BytesOutput = new BytesOutput();
		var list:Array<IMessage> = _output.getlist();
		var len:Int = list.length;
		while (len-->0) {
			var msg:IMessage = list[len];
			if (msg!=null) {
				var data:BytesOutput = msg.encode();
				if (data != null) {
					var d:Bytes = data.getBytes();
					b.writeBytes(d,0,d.length);
				}
			}
		}
		return b.getBytes();
	}
	
}